package com.beiding.jsonanalyzer.analyze.func.openfunc;

import com.beiding.jsonanalyzer.analyze.func.OneFunc;
import com.beiding.jsonanalyzer.analyze.func.base.EasyFunc;
import com.beiding.jsonanalyzer.analyze.func.base.OneFuncAdaptor;

import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * 日期格式化
 *
 * @author 丁常磊
 * @date 2022/5/19 11:23
 */

public class Dateformat {


    public static OneFunc of(Object key, String formatText) {
        java.text.DateFormat format = new SimpleDateFormat(formatText);

        return FuncUtils.buildForEasyFunc(new OneFuncAdaptor<EasyFunc>() {
            @Override
            protected EasyFunc newInstance() {
                return new EasyFunc() {
                    @Override
                    protected Object execute(Object v) {
                        if (v instanceof String) {
                            try {
                                return format.parse((String) v);
                            } catch (ParseException e) {
                                throw new RuntimeException(e);
                            }
                        }

                        return null;
                    }

                    @Override
                    public String toString() {
                        return "dateformat(" + core + "," + formatText + ")";
                    }
                };
            }
        }, key);
    }


}
